﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.MenuCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.MenuHandler
{
    public class AddMenuCommandHandler : IRequestHandler<AddMenuCommand, APIResult<object>>
    {
        private readonly IBaseRepository<MenuManagement> _baseRepository;
        private readonly IMapper _mapper;

        public AddMenuCommandHandler(IBaseRepository<MenuManagement> baseRepository, IMapper mapper)
        {
            _baseRepository = baseRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(AddMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.Success;
            result.Msg = APIEnum.Success.ToString();

            var entity = _mapper.Map<MenuManagement>(request);
            var list = _baseRepository.GetAll().Where(p => p.ParentId == request.ParentId && p.MenuName == request.MenuName);

            if(list.Count()==0)
            {
                entity.UpdateUser = "";
                entity.CreateUser = "admin";
                entity.CreateTime = DateTime.Now;
                entity.UpdateTime = null;
                await _baseRepository.AddAsync(entity);
                result.Code = APIEnum.Success;
                result.Msg = APIEnum.Success.ToString()+"添加菜单成功";
                return await Task.FromResult(result);
            }
            else
            {
                result.Code = APIEnum.Failed;
                result.Msg = APIEnum.Failed.ToString() + "添加菜单名称不唯一";
                return await Task.FromResult(result);
            }
                

        }
    }
}
